const mysql = require('mysql2/promise');

async function debugRoundTiming() {
    let connection;

    try {
        // 数据库连接配置
        const dbConfig = {
            host: 'localhost',
            user: 'root',
            password: '123456',
            database: 'nextjs',
            charset: 'utf8mb4'
        };

        console.log('🔌 连接到数据库...');
        connection = await mysql.createConnection(dbConfig);
        console.log('✅ 数据库连接成功');

        // 检查赤壁期数数据
        console.log('\n📊 检查赤壁期数数据...');
        const [chibiRows] = await connection.execute(`
      SELECT 
        id, 
        startTime, 
        endTime, 
        status,
        TIMESTAMPDIFF(SECOND, NOW(), endTime) as remaining_seconds,
        TIMESTAMPDIFF(SECOND, startTime, endTime) as duration_seconds
      FROM casino_chibi_rounds 
      ORDER BY id DESC 
      LIMIT 5
    `);

        if (chibiRows.length === 0) {
            console.log('⚠️ 没有找到赤壁期数数据');
        } else {
            console.log('赤壁期数数据:');
            chibiRows.forEach(row => {
                const startTime = new Date(row.startTime);
                const endTime = new Date(row.endTime);
                const now = new Date();
                const remainingMs = endTime.getTime() - now.getTime();
                const remainingSeconds = Math.ceil(remainingMs / 1000);

                console.log(`期数${row.id}:`);
                console.log(`  开始时间: ${startTime.toLocaleString()}`);
                console.log(`  结束时间: ${endTime.toLocaleString()}`);
                console.log(`  状态: ${row.status}`);
                console.log(`  期数时长: ${row.duration_seconds}秒 (${(row.duration_seconds / 60).toFixed(1)}分钟)`);
                console.log(`  剩余时间(数据库计算): ${row.remaining_seconds}秒`);
                console.log(`  剩余时间(JS计算): ${remainingSeconds}秒`);
                console.log(`  当前时间: ${now.toLocaleString()}`);
                console.log('---');
            });
        }

        // 检查大小期数数据
        console.log('\n📊 检查大小期数数据...');
        const [diceRows] = await connection.execute(`
      SELECT 
        id, 
        startTime, 
        endTime, 
        status,
        TIMESTAMPDIFF(SECOND, NOW(), endTime) as remaining_seconds,
        TIMESTAMPDIFF(SECOND, startTime, endTime) as duration_seconds
      FROM casino_dice_rounds 
      ORDER BY id DESC 
      LIMIT 5
    `);

        if (diceRows.length === 0) {
            console.log('⚠️ 没有找到大小期数数据');
        } else {
            console.log('大小期数数据:');
            diceRows.forEach(row => {
                const startTime = new Date(row.startTime);
                const endTime = new Date(row.endTime);
                const now = new Date();
                const remainingMs = endTime.getTime() - now.getTime();
                const remainingSeconds = Math.ceil(remainingMs / 1000);

                console.log(`期数${row.id}:`);
                console.log(`  开始时间: ${startTime.toLocaleString()}`);
                console.log(`  结束时间: ${endTime.toLocaleString()}`);
                console.log(`  状态: ${row.status}`);
                console.log(`  期数时长: ${row.duration_seconds}秒 (${(row.duration_seconds / 60).toFixed(1)}分钟)`);
                console.log(`  剩余时间(数据库计算): ${row.remaining_seconds}秒`);
                console.log(`  剩余时间(JS计算): ${remainingSeconds}秒`);
                console.log(`  当前时间: ${now.toLocaleString()}`);
                console.log('---');
            });
        }

        // 分析问题
        console.log('\n🔍 问题分析:');
        console.log('1. 一期应该是10分钟 = 600秒');
        console.log('2. 如果返回19659秒，说明endTime设置有问题');
        console.log('3. 可能的原因:');
        console.log('   - endTime字段值不正确');
        console.log('   - 时区问题');
        console.log('   - 期数创建逻辑有问题');

    } catch (error) {
        console.error('❌ 调试失败:', error);
    } finally {
        if (connection) {
            await connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }
}

// 运行调试
debugRoundTiming()
    .then(() => {
        console.log('✅ 调试完成');
        process.exit(0);
    })
    .catch((error) => {
        console.error('❌ 调试失败:', error);
        process.exit(1);
    });
